package modules.program.model;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;

import etc.Config;
import etc.Language;


@SuppressWarnings("javadoc")
public class Rest
{

	// Types
	public static final int TYPE_POST   = 1;
	public static final int TYPE_GET    = 2;
	public static final int TYPE_PUT    = 3;
	public static final int TYPE_DELETE = 4;

	// Config and Essentials
	private int type;
	private String apiUrl;
	private String query;

	// Method depending variables
	private String path;
	private String method;
	private boolean doOutput;

	// Result
	private String result;

	public void setType(int type)
	{
		this.type = type;
	}

	public void setApiUrl(String apiUrl)
	{
		this.apiUrl = apiUrl;
	}

	public void setQuery(String query)
	{
		this.query = query;
	}
	
	private void initialize()
	{
		// Set the request path
		this.path = this.apiUrl+"?"+this.query;

		// Set we want do do an output in most methods
		this.doOutput = true;

		// Switch the type for type depending initialisations
		switch(this.type)
		{
			case TYPE_POST:
				this.method = "POST";
				break;

			case TYPE_GET:
				this.method = "GET";
				this.doOutput = false;
				break;

			case TYPE_PUT:
				this.method = "PUT";
				break;

			case TYPE_DELETE:
				this.method = "DELETE";
				this.doOutput = false;
				break;

			default:
				// Unknown request type
				throw new RuntimeException("Unenxpected request type!");
		}
	}
	
	public void doRequest()
	{
		// Initialize request data
		this.initialize();

		try {
			// Open the connection
			HttpURLConnection connection = (HttpURLConnection)new URL(this.path).openConnection();

			// Set whether we want to send something to the connection
			connection.setDoOutput(this.doOutput);

			// Set the method
			connection.setRequestMethod(this.method);

			// Check whether we want to send something
			if(this.doOutput)
			{
				// Send something
				connection.getOutputStream().write("".getBytes("UTF-8"));
			}

			// Try to read the result
			InputStream inputStream = connection.getInputStream();

			// Make a string of the result
			this.result = new Scanner(inputStream).useDelimiter("\\A").next();
		}
		catch(IOException e)
		{
			this.result = Language.get("Program.Rest.ConnectionFailed");
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public String getResult()
	{
		return this.result;
	}
	
	public static String call(String query, int type)
	{
		Rest api = new Rest();
		api.setApiUrl(Config.get("Website.ApiUrl"));
		api.setType(type);
		api.setQuery(query);
		api.doRequest();
		
		return api.getResult();
	}

}